/**
 * @copyright Copyright (C) 2021 XH Technology Inc. All Rights Reserved 
 * @file common.h
 * @author Fan Junmin
 * @version  V1.0
 * @date  03/19/2021
 * @brief  程序常用的公用出来模块
 * Common utility module providing frequently used functions and definitions
 * This header file serves as a centralized collection of common utilities,
 * type definitions, and system interfaces used throughout the application
 */

/* 
 * Include guard to prevent multiple inclusions of this header file
 * This macro ensures the compiler processes the content only once,
 * preventing redefinition errors and improving compilation efficiency
 * The double underscore naming follows conventional header guard patterns
 */
#ifndef __COMMON_H__

/* 
 * Define the include guard macro to mark this header as processed
 * Once defined, subsequent inclusions of this file will be skipped
 * during the preprocessor phase, ensuring single declaration processing
 */
#define __COMMON_H__

/************************************include*********************************/
/* 
 * Include standard C library headers for fundamental system operations
 * These headers provide essential functions for I/O, memory management,
 * string operations, process control, and system interface operations
 */

/* 
 * Standard Input/Output header for file operations and console I/O
 * Provides functions like printf, fopen, fread, fwrite for data handling
 */
#include <stdio.h>

/* 
 * Standard Library header for memory allocation and utility functions
 * Includes malloc, free, atoi, rand and other general purpose functions
 */
#include <stdlib.h>

/* 
 * String Operations header for string manipulation and memory operations
 * Provides strcpy, strcmp, strlen, memset, memcpy for string and memory handling
 */
#include <string.h>

/* 
 * POSIX Threads header for multi-threading and synchronization support
 * Enables creation and management of threads, mutexes, and thread coordination
 */
#include <pthread.h>

/* 
 * Signal Handling header for process signal management and interrupt handling
 * Provides functions to handle and send signals between processes and threads
 */
#include <signal.h>

/* 
 * Time and Date header for time-related operations and date calculations
 * Includes functions for getting current time, time formatting, and delays
 */
#include <time.h>

/* 
 * UNIX Standard header for POSIX operating system API access
 * Provides access to system calls, file operations, and process control functions
 */
#include <unistd.h>

/* 
 * System Time header for time structure definitions and timezone handling
 * Defines struct timeval and related functions for precise time measurement
 */
#include <sys/time.h>

/* 
 * Input/Output Control header for device control and terminal operations
 * Provides ioctl function for device-specific operations and parameter control
 */
#include <sys/ioctl.h>

/* 
 * File Locking header for file locking and synchronization mechanisms
 * Enables advisory file locking to prevent concurrent access conflicts
 */
#include <sys/file.h>

/* 
 * Fixed-width Integer Types header for precise integer size specifications
 * Defines int8_t, uint16_t, etc. for portable fixed-size integer operations
 */
#include <stdint.h>

/* 
 * Variable Arguments header for functions with variable number of parameters
 * Enables creation of functions like printf that accept variable arguments
 */
#include <stdarg.h>

/* 
 * System Types header for basic system data type definitions
 * Defines pid_t, size_t, and other system-specific type aliases
 */
#include <sys/types.h>

/* 
 * File Status header for file information and permission operations
 * Provides stat function and related structures for file metadata access
 */
#include <sys/stat.h>

/********************************define**************************************/

/* 
 * Define boolean type enumeration for true/false values
 * This provides a standardized way to represent boolean values
 * throughout the application, improving code readability and consistency
 */
typedef enum
{
    FALSE = 0,    /* Boolean false value represented as integer 0 */
    TRUE = !FALSE /* Boolean true value represented as logical negation of false */
} bool;

/* 
 * Define true macro if not already defined by other headers
 * This ensures compatibility with different compilation environments
 * and provides consistent boolean representation across the codebase
 */
#ifndef true
#define true TRUE
#endif

/* 
 * Define false macro if not already defined by other headers
 * Maintains consistency with the boolean enumeration definition
 * and ensures uniform false representation in conditional statements
 */
#ifndef false
#define false FALSE
#endif

/* 
 * Define inline macro for function inlining optimization
 * This encourages compiler to inline small frequently-called functions
 * improving performance by eliminating function call overhead
 */
#ifndef inline
#define inline __inline
#endif

/********************************enum****************************************/

/********************************typedef data********************************/

/* 
 * Define platform-independent fixed-width integer type aliases
 * These typedefs ensure consistent integer sizes across different
 * platforms and compilers, improving code portability and reliability
 */

/* 
 * 64-bit unsigned integer type definition
 * Used for large numerical values and bit manipulation operations
 * Guarantees exactly 64 bits of storage regardless of platform
 */
typedef unsigned long int u64;

/* 
 * 32-bit unsigned integer type definition  
 * Standard size for general-purpose integers and array indices
 * Provides consistent 32-bit storage across different architectures
 */
typedef unsigned int u32;

/* 
 * 16-bit unsigned integer type definition
 * Used for smaller numerical values and memory-efficient storage
 * Ensures exactly 16 bits of storage for portability
 */
typedef unsigned short int u16;

/* 
 * 8-bit unsigned integer type definition
 * Smallest integer type for byte-level operations and compact storage
 * Guarantees 8-bit storage for character and byte array handling
 */
typedef unsigned char u8;

/* 
 * Standard 8-bit unsigned integer type alias
 * Compatible with stdint.h naming convention for consistency
 * Used for precise 8-bit unsigned integer operations
 */
typedef unsigned char uint8_t;

/* 
 * Standard 16-bit unsigned integer type alias  
 * Follows stdint.h naming convention for cross-platform compatibility
 * Ensures exact 16-bit width for portable integer operations
 */
typedef unsigned short uint16_t;

/********************************typedef function****************************/

/********************************typedef struct******************************/

/*******************************struct***************************************/

/************************************user file*******************************/

/*******************************External interface***************************/

/* 
 * Read entire file content into a dynamically allocated string buffer
 * This function opens a file, determines its size, allocates memory,
 * and reads the complete content into a null-terminated string
 * 
 * @param filename: Path to the file to be read
 * @return: Pointer to dynamically allocated buffer containing file content
 *          Returns NULL on failure (file not found, read error, or memory allocation failure)
 * 
 * The caller is responsible for freeing the returned buffer using free()
 * to prevent memory leaks after the data is no longer needed
 */
char *read_file(const char *filename);

/* 
 * Write data buffer to specified file with complete content replacement
 * This function creates or overwrites a file and writes the entire
 * content from the provided buffer in a single atomic operation
 * 
 * @param filename: Path to the file to be written or created
 * @param buf: Null-terminated string buffer containing data to write
 * @return: Integer status code indicating operation success (0) or failure (-1)
 * 
 * On failure, the function returns -1 and the original file remains unchanged
 * ensuring data integrity in case of write operations interruptions
 */
int write_file(const char *filename, const char *buf);

/* 
 * Check if specified file exists and is accessible in the filesystem
 * This function verifies file existence using stat system call
 * and returns accessibility status without attempting to open the file
 * 
 * @param filepath: Complete path to the file to check for existence
 * @return: Integer status code - 0 if file exists, -1 if file doesn't exist or is inaccessible
 * 
 * The function only checks existence and basic accessibility, not read/write permissions
 * or file content validity, providing a lightweight existence verification
 */
int is_file_exist(const char *filepath);

/* 
 * Check if specified directory exists and is accessible in the filesystem
 * This function verifies directory existence using stat system call
 * and confirms it is indeed a directory rather than a regular file
 * 
 * @param dirpath: Complete path to the directory to check for existence
 * @return: Integer status code - 0 if directory exists, -1 if directory doesn't exist or is inaccessible
 * 
 * Returns success only if the path exists and represents a directory,
 * distinguishing between files and directories in the verification process
 */
int is_dir_exist(const char *dirpath);

/* 
 * Suspend execution for specified number of milliseconds with high precision
 * This function provides millisecond-level sleep functionality using
 * nanosleep system call for accurate timing and minimal CPU utilization
 * 
 * @param ms: Number of milliseconds to suspend program execution
 * @return: void
 * 
 * Unlike standard sleep functions, this provides millisecond precision
 * and is not affected by system load or process scheduling variations
 */
void sleep_ms(unsigned int ms);

/* 
 * Suspend execution for specified number of seconds with process yielding
 * This function provides second-level sleep using standard sleep call
 * allowing other processes to execute during the suspension period
 * 
 * @param s: Number of seconds to suspend program execution
 * @return: void
 * 
 * During suspension, the process yields CPU to other runnable processes
 * improving overall system efficiency and resource utilization
 */
void sleep_s(unsigned int s);

/* 
 * Get current system time in milliseconds since epoch with high precision
 * This function retrieves system time using gettimeofday for microsecond
 * accuracy and converts to milliseconds for consistent time representation
 * 
 * @return: long long value representing milliseconds since Unix epoch (January 1, 1970)
 * 
 * The return value is suitable for timing measurements, performance profiling,
 * and timestamp generation with millisecond resolution accuracy
 */
long long get_system_time_ms(void);

/* 
 * Get current system time in microseconds since epoch with maximum precision
 * This function uses gettimeofday system call to obtain the highest
 * available time resolution for precise timing measurements and profiling
 * 
 * @return: u64 (64-bit unsigned) value representing microseconds since Unix epoch
 * 
 * Provides microsecond resolution for high-precision timing requirements
 * such as performance benchmarking and real-time operation timing
 */
u64 get_system_time_us(void);

/* 
 * Calculate time difference in microseconds between two time measurements
 * This function computes the absolute time difference between two
 * microsecond-level timestamps, handling potential counter wrap-around
 * 
 * @param current: Later timestamp in microseconds obtained from get_system_time_us
 * @param last: Earlier timestamp in microseconds for difference calculation
 * @return: u64 (64-bit unsigned) value representing absolute time difference in microseconds
 * 
 * The function ensures correct difference calculation even when system
 * time counters wrap around, providing reliable elapsed time measurements
 */
u64 get_system_time_absoffset(u64 current, u64 last);

/* 
 * Get current minute of the hour from system time for time-based operations
 * This function extracts the minute component (0-59) from the current
 * system time for scheduling and time-dependent logic implementations
 * 
 * @return: Integer value representing current minute of the hour (0-59)
 * 
 * Useful for implementing minute-based scheduling, logging timestamps,
 * and time-dependent application behavior without full date processing
 */
int system_minute(void);

/* 
 * Execute system command with basic error handling and status reporting
 * This function wraps the standard system() call with additional
 * error checking and consistent return value processing
 * 
 * @param cmd: Null-terminated string containing the shell command to execute
 * @return: Integer status code matching the shell command exit status
 * 
 * Returns the exit status of the executed command, with -1 indicating
 * that the system function itself failed to execute the command
 */
int my_system(const char *cmd);

/* 
 * Execute formatted system command with variable arguments like printf
 * This function provides printf-style formatting for system commands
 * enabling dynamic command construction with variable parameters
 * 
 * @param fmt: Format string specifying command structure with placeholders
 * @param ...: Variable arguments to be substituted into the format string
 * @return: Integer status code matching the shell command exit status
 * 
 * Supports all standard printf format specifiers for flexible command
 * generation with dynamic parameters and conditional command construction
 */
int shell_system(const char *fmt, ...);

/* 
 * Execute formatted system command and capture output into buffer
 * This function combines command execution with output capture using
 * popen, storing the command output in the provided buffer
 * 
 * @param buf: Character buffer to store command output results
 * @param size: Maximum size of the output buffer in bytes
 * @param fmt: Format string for command generation with placeholders
 * @param ...: Variable arguments for command formatting
 * @return: Integer status code indicating success (0) or failure (-1)
 * 
 * The captured output is null-terminated and truncated to fit the buffer
 * size, ensuring safe string handling and preventing buffer overflows
 */
int shell_popen(char *buf,int size,const char *fmt, ...);

/* 
 * Convert numeric string to integer value with basic error handling
 * This function parses a string containing numeric characters and
 * converts it to corresponding integer value using standard conversion
 * 
 * @param ch: Null-terminated string containing numeric characters to convert
 * @return: Integer value representation of the numeric string
 * 
 * For invalid numeric strings, the behavior depends on the underlying
 * atoi implementation, typically returning 0 for non-numeric input
 */
int char_to_int(char *ch);

/* 
 * Convert integer value to string representation with null termination
 * This function converts an integer to its string representation
 * and stores it in the provided character buffer as null-terminated string
 * 
 * @param value: Integer value to be converted to string representation
 * @param ch: Character buffer to store the resulting string
 * @return: void
 * 
 * The caller must ensure the buffer is large enough to hold the
 * maximum possible integer string representation including null terminator
 */
void int_to_char(int value, char *ch);

/* 
 * Convert numeric string to floating-point value with basic parsing
 * This function parses a string containing floating-point representation
 * and converts it to corresponding float value using standard conversion
 * 
 * @param ch: Null-terminated string containing floating-point number to convert
 * @return: Float value representation of the numeric string
 * 
 * Handles standard floating-point formats including decimal points
 * and scientific notation depending on the underlying conversion implementation
 */
float char_to_float(char *ch);

/* 
 * Split source string into tokens using specified separator character
 * This function tokenizes a source string using the provided separator
 * and stores pointers to each token in the destination array
 * 
 * @param src: Source string to be split into tokens
 * @param separator: Character used as delimiter for token separation
 * @param dest: Array of character pointers to store token addresses
 * @param num: Pointer to integer that will receive the token count
 * @return: void
 * 
 * The source string is modified by replacing separators with null characters
 * and the dest array contains pointers to the beginning of each token
 * The num parameter returns the actual number of tokens found and stored
 */
void split(char *src, const char *separator, char **dest, int *num);

/* 
 * End of include guard section
 * This completes the header file content and ensures subsequent
 * inclusions are skipped due to the previously defined __COMMON_H__ macro
 */
#endif